package com.next

import grails.transaction.Transactional
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked

@CompileStatic
@TypeChecked
class OpportunityTeamService
{
    static scope = "singleton"

    @Transactional
    Boolean initTeam(Opportunity opportunity, Territory territory)
    {
        def territoryTeams
        while (territory)
        {
            territoryTeams = TerritoryTeam.findAll("from TerritoryTeam where territory.id = ?", [territory?.id])
            for (
                team in
                    territoryTeams)
            {
                def opportunityTeam = OpportunityTeam.find("from OpportunityTeam where opportunity.id = ? and user.id=?", [opportunity?.id, team?.user?.id])
                if (!opportunityTeam)
                {
                    opportunityTeam = new OpportunityTeam()
                    opportunityTeam.user = team?.user
                    opportunityTeam.opportunity = opportunity
                    if (opportunityTeam.validate())
                    {
                        opportunityTeam.save()
                    }
                    else
                    {
                        println opportunityTeam.errors
                    }
                }
            }
            territory = territory?.parent
        }
    }
}
